<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增 GitHub 配置
      </el-button>
    </div>

    <!-- 配置列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="配置名称" min-width="150">
        <template slot-scope="{row}">
          <strong>{{ row.name }}</strong>
          <div v-if="row.description" style="font-size: 12px; color: #999;">
            {{ row.description }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="GitHub 用户名" width="150">
        <template slot-scope="{row}">
          <el-tag type="info">@{{ row.username }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="仓库配置" width="200">
        <template slot-scope="{row}">
          <div style="font-size: 13px;">
            <p><strong>前缀:</strong> {{ row.repo_prefix || '无' }}</p>
            <p><strong>分支:</strong> {{ row.default_branch }}</p>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="仓库类型" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.private_repo ? 'warning' : 'success'" size="small">
            {{ row.private_repo ? '私有' : '公开' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
            {{ row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="最后使用" width="160" align="center">
        <template slot-scope="{row}">
          <span v-if="row.last_used_at">{{ row.last_used_at }}</span>
          <span v-else style="color: #999;">未使用</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="160" align="center">
        <template slot-scope="{row}">
          {{ row.create_at }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            :type="row.is_active ? 'warning' : 'success'"
            size="mini"
            @click="handleToggleActive(row)"
          >
            {{ row.is_active ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- GitHub 配置对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="form.name" placeholder="如：主账号" />
        </el-form-item>

        <el-form-item label="GitHub 用户名" prop="username">
          <el-input v-model="form.username" placeholder="GitHub 用户名（非邮箱）" />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            填写 GitHub 用户名，不是邮箱地址。可留空，系统会自动从 Token 获取。
          </div>
        </el-form-item>

        <el-form-item label="Access Token" prop="access_token">
          <el-input
            v-model="form.access_token"
            type="password"
            placeholder="GitHub Personal Access Token"
            show-password
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            ⚠️ 必须使用 <strong>Classic Token（经典令牌）</strong>，勾选 repo 权限。
            <el-link
              type="primary"
              href="https://github.com/settings/tokens"
              target="_blank"
              :underline="false"
            >
              创建 Classic Token
            </el-link>
          </div>
        </el-form-item>

        <el-form-item label="仓库名前缀">
          <el-input v-model="form.repo_prefix" placeholder="如：static-" />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            实际仓库名为：{{ form.repo_prefix || '' }}example-com
          </div>
        </el-form-item>

        <el-form-item label="默认分支">
          <el-input v-model="form.default_branch" placeholder="main" />
        </el-form-item>

        <el-form-item label="私有仓库">
          <el-switch v-model="form.private_repo" />
          <span style="margin-left: 10px; font-size: 12px; color: #999;">
            {{ form.private_repo ? '创建私有仓库' : '创建公开仓库' }}
          </span>
        </el-form-item>

        <el-form-item label="配置描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="可选"
          />
        </el-form-item>

        <el-form-item label="启用状态">
          <el-switch v-model="form.is_active" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGitHubConfigs, getGitHubConfig, createGitHubConfig, updateGitHubConfig, deleteGitHubConfig } from '@/api/static_web_github'

export default {
  name: 'GitHubConfig',
  data() {
    return {
      list: [],
      listLoading: true,
      dialogVisible: false,
      loading: false,
      isEdit: false,
      form: {
        name: '',
        username: '',
        access_token: '',
        repo_prefix: '',
        default_branch: 'main',
        private_repo: false,
        description: '',
        is_active: true
      },
      rules: {
        name: [
          { required: true, message: '请输入配置名称', trigger: 'blur' }
        ],
        username: [
          { required: false } // 改为非必填，系统会自动从 Token 获取
        ],
        access_token: [
          { required: true, message: '请输入 Access Token', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑 GitHub 配置' : '新增 GitHub 配置'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getGitHubConfigs().then(response => {
        this.list = response.data || []
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleCreate() {
      this.resetForm()
      this.isEdit = false
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      // 调用 API 获取完整的配置信息（包含完整 token）
      this.loading = true
      getGitHubConfig(row.id).then(response => {
        this.form = { ...response.data }
        this.isEdit = true
        this.dialogVisible = true
        this.loading = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      }).catch(() => {
        this.loading = false
        this.$message.error('获取配置信息失败')
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },
    resetForm() {
      this.form = {
        name: '',
        username: '',
        access_token: '',
        repo_prefix: '',
        default_branch: 'main',
        private_repo: false,
        description: '',
        is_active: true
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },
    handleSubmit() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) return

        this.loading = true
        try {
          if (this.isEdit) {
            await updateGitHubConfig(this.form.id, this.form)
            this.$message.success('配置更新成功')
          } else {
            await createGitHubConfig(this.form)
            this.$message.success('配置创建成功')
          }
          this.getList()
          this.handleClose()
        } catch (error) {
          console.error('保存失败:', error)
        } finally {
          this.loading = false
        }
      })
    },
    handleToggleActive(row) {
      const action = row.is_active ? '禁用' : '启用'
      this.$confirm(`确定要${action}该配置吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { ...row, is_active: !row.is_active }
        updateGitHubConfig(row.id, data).then(() => {
          this.$message.success(`${action}成功`)
          this.getList()
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该配置吗？删除后无法恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteGitHubConfig(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
</style>
